<template>
  <div class="common-layout">
    <el-container>
      <el-header style="
          border-bottom: 1px solid #ccc;
          background-color: #fff;
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
        <div class="common-layout-header-title" style="flex-shrink: 0; padding-left: 10px">
          课程管理 
        </div>
        <div style="display: flex; align-items: center">
          <!-- <el-button plain type="danger" size="small" 
          v-if="showCheckbox==false"
           style="margin-right: 10px; height: 30px; line-height: 32px" @click="batchDelete">
  批量删除
</el-button>
<el-button plain type="primary" size="small" 
 v-if="showCheckbox"
           style="margin-right: 10px; height: 30px; line-height: 32px" @click="quxiaoshanchu">
  取消删除
</el-button> -->
          
          <el-button plain type="primary" size="small" 
            style="margin-right: 10px; height: 30px; line-height: 32px" @click="xinzeng">
            新增题目
          </el-button>
          
          <el-button plain type="primary" size="small" 
          style="margin-right: 10px; height: 30px; line-height: 32px"
          @click="importDialogVisible = true">
          文档导入
        </el-button>


        
           <!-- <el-button plain type="primary" size="small" 
            style="margin-right: 10px; height: 30px; line-height: 32px" @click="xiugai">
            修改题目
          </el-button> -->

          
          <el-dialog 
          v-model="tianjia" 
          :title="timu" 
          width="90%" 
          :close-on-click-modal="false"
          @close="resetForm"
        >
            <div class="ti">
              <el-form :model="forms" :rules="rules" ref="formRef">
              <el-row :gutter="20">
                <!-- 题目类型 -->
                <el-col :span="6">
                  <el-form-item label="题目类型  :"   :label-width="formLabelWidth" prop="subjectType">
                    <el-select v-model="forms.subjectType" @click="hc()" placeholder="选择题目类型">
                      <el-option
                        v-for="nan in xuanze"
                        :key="nan.value"
                        :label="nan.nanName"
                        :value="nan.nanId"
                      />
                    </el-select>
                    <!-- 显示选择的题目类型标签 -->
                    <!-- <div style="margin-top: 10px;">
                      <el-tag 
                        v-for="option in selectedOption" 
                        :key="option.value" 
                        closable 
                        @close="removeTag(option)"
                        style="margin-right: 5px;"
                      >
                         {{ option.label }}  
                      </el-tag>
                    </div> -->
                  </el-form-item>
                </el-col>

                <!-- 题目标签 -->
                <el-col :span="6">
                  <el-form-item label="题目标签  :" :label-width="formLabelWidth" prop="subjectLabel">
                    <el-select v-model="labelsString" multiple placeholder="选择题目标签" @change="handleChange">
                       <el-option
                        v-for="item in subjectLabel"
                        :key="item.labelId"
                        :label="item.labelName"
                        :value="item.labelId"
                      />
                    </el-select>
                    <!-- 显示选择的题目类型标签 -->
                    <!-- <div style="margin-top: 10px;">
                      <el-tag 
                        v-for="option in selectedOption" 
                        :key="option.value" 
                        closable 
                        @close="removeTag(option)"
                        style="margin-right: 5px;"
                      >
                         {{ option.label }}  
                      </el-tag>
                    </div> -->
                  </el-form-item>
                </el-col>

                <!-- 选择班级 -->
                <el-col :span="6">
                  <el-form-item label="专业名称 :" prop="subjectMajor" :label-width="formLabelWidth">
                    <el-select v-model="forms.subjectMajor" placeholder="选择专业">
                       <el-option
                        v-for="item in zhaun"
                        :key="item.value"
                        :label="item.directionName"
                        :value="item.directionId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                 <!-- 选择试题难度 -->
                <el-col :span="6">
                  <el-form-item label="试题难度 :" prop="subjectLv" :label-width="formLabelWidth">
                    <el-select v-model="forms.subjectLv" placeholder="选择难度">
                       <el-option
                        v-for="nan in lxData"
                        :key="nan.value"
                        :label="nan.nanName"
                        :value="nan.nanId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>



              </el-row>
              <el-row :gutter="20"> 
              <el-col :span="12">
              <el-form-item label="题目名称  :"   prop="subjectName" :label-width="formLabelWidth"  >
                <el-input type="textarea" :rows="2" v-model="forms.subjectName" autocomplete="off" placeholder="请输入题目名称"/>
              </el-form-item>
            </el-col>
            </el-row>
               <div v-if="forms.subjectType == 2 || forms.subjectType == 1  || forms.subjectType == '单选题'  || forms.subjectType == '多选题' ">
                <el-row :gutter="24"> 
                  <el-col :span="12">
                    <el-form-item label="选项A  :" prop="optionA" :label-width="formLabelWidth">
                      <el-input type="textarea" :rows="2" v-model="forms.optionA" autocomplete="off" placeholder="请输入选项A"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="选项B :" prop="optionB" :label-width="formLabelWidth">
                      <el-input type="textarea" :rows="2" v-model="forms.optionB" autocomplete="off" placeholder="请输入选项B"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="选项C  :" prop="optionC" :label-width="formLabelWidth">
                      <el-input type="textarea" :rows="2" v-model="forms.optionC" autocomplete="off"  placeholder="请输入选项C"/>
                    </el-form-item>
                  </el-col>
                  
                  <el-col :span="12">
                    <div style="width: 100%; height: 10px; margin-left: 10px; ">
                    <el-form-item label="选项D  :" prop="optionD" :label-width="formLabelWidth">
                      <el-input type="textarea" :rows="2" v-model="forms.optionD" autocomplete="off"  placeholder="请输入选项D"/>
                    </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <div v-if="forms.subjectType == 1  || forms.subjectType == '多选题' ">
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="选项E  :"  :label-width="formLabelWidth">
                        <el-input type="textarea" :rows="2" v-model="forms.optionE" autocomplete="off" placeholder="请输入选项E" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="选项F  :"  :label-width="formLabelWidth">
                        <el-input type="textarea" :rows="2" v-model="forms.optionF" autocomplete="off" placeholder="请输入选项F" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>
              <div v-if="forms.subjectType == 0   || forms.subjectType == '判断题' ">
          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="正确  :" prop="optionA" :label-width="formLabelWidth" >
                <el-input type="textarea" :rows="2" v-model="forms.optionA" autocomplete="off" placeholder="请输入正确的答案"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="错误  :" prop="optionB" :label-width="formLabelWidth">
                <el-input type="textarea" :rows="2" v-model="forms.optionB" autocomplete="off" placeholder="请输入错误的答案"/>
              </el-form-item>
            </el-col>
          </el-row> -->
          </div>
              <el-row :gutter="20"> 
              <el-col :span="12">
               <el-form-item label="题目答案 :" prop="subjectAnswer" :label-width="formLabelWidth">
              <el-select v-model="forms.subjectAnswer" 
                        :multiple="forms.subjectType === 1 || forms.subjectType === '多选题'" 
                        placeholder="请选择答案">
                <el-option v-if="forms.subjectType !== 0 && forms.subjectType !== '判断题'" label="A" value="A" />
                <el-option v-if="forms.subjectType !== 0 && forms.subjectType !== '判断题'" label="B" value="B" />
                <el-option v-if="forms.subjectType !== 0 && forms.subjectType !== '判断题'" label="C" value="C" />
                <el-option v-if="forms.subjectType !== 0 && forms.subjectType !== '判断题'" label="D" value="D" />
                <el-option v-if="forms.subjectType === 1 || forms.subjectType === '多选题' && forms.optionE" label="E" value="E" />
                <el-option v-if="forms.subjectType === 1 || forms.subjectType === '多选题' && forms.optionF" label="F" value="F" />
                <el-option v-if="forms.subjectType === 0 || forms.subjectType === '判断题'" label="对" value="对" />
                <el-option v-if="forms.subjectType === 0 || forms.subjectType === '判断题'" label="错" value="错" />
              </el-select>
            </el-form-item>
              </el-col>
              </el-row>
      <div class="tu">
  <el-form-item label="图片 :" :label-width="formLabelWidth">            
    <el-upload 
      ref="uploadRef" 
      action="/api/user/upload" 
      :show-file-list="false"
      :on-success="uploadSuccess"
      :headers="{'Authorization': usertonken.token}"
      :before-upload="beforeAvatarUpload"
    >
      <div class="tt">
        <img v-if="subjectImage" :src="subjectImage" class="avatar-uploader" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </div>
    </el-upload>
  </el-form-item>
</div>

            </el-form>

          

            </div>
            <!-- 按钮 -->
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="quxiao">取消</el-button>
                <el-button type="primary" @click="quer">
                  确认
                </el-button>
              </div>
            </template>
          </el-dialog>

          <!-- <el-input placeholder="请输入内容" size="small" v-model="courseName"
            style="margin-right: 10px; width: 150px; height: 30px" />
          <el-button type="primary" @click="getNameCourseList" style="margin-left: 0; height: 30px">
            搜索
          </el-button> -->
        </div>
      </el-header>
      <div class="body-header">
        <ul>
          <li>专业:</li>
          <li :class="{ 'header-01': zyNum == -1 }" @click="
            zyNum = -1;
            dj3();
          ">
            <div @click="zz(0)">全部</div>
          </li>
          <li v-for="(item, index) in zhuanye" :key="index" :class="{ 'header-01': zyNum == index }" @click="
            zyNum = index;
          zz(item.directionId);
          ">
            {{ item.directionName }}
          </li>
        </ul>
      </div>
     
   
    
      <div class="body-header">
    <ul>
      <li> 知识点:</li>
      <li 
        v-for="(item, index) in subjecLabel" 
        :key="index" 
        :class="{ 'header-01': selectedSubjects.some(selectedItem => selectedItem.labelName === item.labelName) }" 
        @click="toggleSubject(item)"
      >
        {{ item.labelName }}
      </li>
    </ul>
  </div>

  <div class="body-header">
        <ul>
          <li>难度:</li>
          <li :class="{ 'header-01': lxNum == -1 }" @click="
            lxNum = -1;
          dj3();
          ">
            <div @click="dj1(0)">全部</div>
          </li>
          <li v-for="(item, index) in lxData" :key="index" :class="{ 'header-01': lxNum == index }" @click="
            lxNum = index;
          dj1(item.nanId);
          ">
            {{ item.nanName }}
          </li>
        </ul>
      </div>
       
        
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index="0">全部题型</el-menu-item>
          <el-menu-item index="1">单选题</el-menu-item>
          <el-menu-item index="2">多选题</el-menu-item>
          <el-menu-item index="3">判断题</el-menu-item>
        </el-menu>
        <div v-if="activeIndex === '0'" v-loading="loading">
          <div v-for="(item, index) in sysSubiect" :key="index" class="common-course-Quest-item" v-loading="loading">
            <el-checkbox v-if="showCheckbox" v-model="item.selected"></el-checkbox>
            <div class="common-course-Quest-item-left">
              <div class="common-course-Quest-item-ti">
                <div class="common-course-Quest-item-title">
                题型：<div v-if="item.subjectType == 2">单选题</div>
                <div v-if="item.subjectType == 1">多选题</div>
                <div v-if="item.subjectType == 0">判断题</div>
                
              </div>
              <div class="common-course-Quest-item-title">
                专业： <div>{{ item.direction.directionName }}</div>
              </div>
              <div class="common-course-Quest-item-title">
                难度：<div>
                  <el-rate class="el-rate"
                    v-model="item.subjectLv"
                    disabled
                    :max="3"
                    text-color="#ff9900">
                  </el-rate>
                  </div>
              </div>
              <div class="common-course-Quest-item-title">
                <div>答案：{{ item.subjectAnswer }}</div>
              </div>
              <div class="common-course-Quest-item-title" v-if="item.sysSubjectLabel && item.sysSubjectLabel.length > 0">
                <div>知识点：</div>
                <div v-for="(xx,index) in item.sysSubjectLabel" :key="index" class="common-course-Quest-item-title_point" >
                  <el-text truncated>{{ xx.labelName }}</el-text>
                </div>
                
              </div>
              
              </div>
              
              <div class="common-course-Quest-item-title_caozuo">
                <el-button type="primary" plain @click="xiugai(item)">修改</el-button>
              <el-button type="danger" plain @click="shan(item.subjectId)">删除</el-button>
              </div>
              
            </div>
            <div  class="separator"></div>
            <div>
              <div class="common-course-Quest-item-title_ti"><span>题目：</span>{{ item.subjectName }}</div>
              <div class="common-course-Quest-item-option">
                <div class="option-container">
                  <div v-if="item.optionC === null||item.optionC == ''">
                     <div class="option-text">{{item.optionA  }}</div>
                     <div class="option-text">{{item.optionB  }}</div>
                  </div>
                  <div v-if="item.optionC != null&&item.optionC!=''">
                    <div class="option-text" style="font-weight: lighter;">{{item.optionA ? 'A. ' + item.optionA : ''  }}</div>
                    <div class="option-text" style="font-weight: lighter;">{{item.optionB ? 'B. ' + item.optionB : ''  }}</div>
                  </div>
                 
                  <div class="option-text" style="font-weight: lighter;">{{item.optionC ? 'C. ' + item.optionC : ''  }}</div>
                  <div  class="option-text" style="font-weight: lighter;">{{item.optionD ? 'D. ' + item.optionD : ''  }}</div>
                  <div  class="option-text" style="font-weight: lighter;">{{item.optionE ? 'E. ' + item.optionE : '' }}</div>
                  <div  class="option-text" style="font-weight: lighter;">{{item.optionF ? 'F. ' + item.optionF : ''  }}</div>
                </div>
              </div>
              <div v-if="item.subjectImage != null">
                <div class="tupian">
                  <el-image :src= item.subjectImage style="width: 300px; height: 300px;" :preview-src-list="[item.subjectImage]"></el-image></div>
              </div>
              
            </div>
            <div class="separator01"></div>
            <div class="fabu">
              <div class="fabuxinxi">
                <div v-if="item.user!=null">发布人：{{ item.user.nickName }}</div>
              </div>
              <div class="fabuxinxi">
                <div>发布时间：{{ item.createtime }}</div>
              </div>
              <div class="fabuxinxi">
                <div v-if="item.reviser!=null">修改人：{{ item.reviser }}</div>
              </div>
              <div class="fabuxinxi">
                <div v-if="item.changetime!=null">修改时间：{{ item.changetime }}</div>
              </div>
            </div>
          </div>
          <!-- 分页条 -->
        <el-pagination
        v-model:current-page="pageNum" 
        v-model:page-size="pageSize" 
        :page-sizes="[5, 10 ,15, 20]"
        layout="jumper, total, sizes, prev, pager, next" background 
        :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" 
        style="margin-top: 20px; 
        justify-content: flex-end" />
        
        
        </div>
        <div v-if="activeIndex === '1'">
          <!-- 单选题内容 -->
          
          <Radio :someNumber=ww />
        </div>
        <div v-else-if="activeIndex === '2'">
          <!-- 多选题内容 -->
          <MultipleChoices :someNumber=ww />
        </div>
        <div v-else-if="activeIndex === '3'">
          <!-- 判断题内容 -->
          <Judgment :someNumber=ww />
        </div>
     
      
    </el-container>
  </div>


  <el-dialog 
  v-model="importDialogVisible" 
  title="导入数据" 
  width="40%"
  :close-on-click-modal="false"
>
<el-upload
  class="upload-demo"
  drag
  action=""
  :auto-upload="false"
  :on-change="importExcel"
  
>
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
  <div slot="tip" class="el-upload__tip">不可超过<br /> 500KB</div>
</el-upload>
  
  <!-- 下载模板按钮 -->
  <el-button type="primary" @click="downloadTemplate">下载模板</el-button>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="importDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitUpload">确定</el-button>
    </div>
  </template>
</el-dialog>
</template>

<script setup>
import Radio from '@/view/common/course/ObjectiveQuestions/Radio.vue';
import MultipleChoices from '@/view/common/course/ObjectiveQuestions/MultipleChoices.vue';
import Judgment from "@/view/common/course/ObjectiveQuestions/Judgment.vue";

import { ref, reactive,computed,watch,onMounted } from 'vue'
import { ElTag } from 'element-plus';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import {selectAllQuestionType,selectAllQuestionTypeList,selectSubjectByLabelId,selectMajorList,importSubject,updatePicService} from '@/api/QuestionBankManagement/AllQuestionTypes'
import { data } from 'jquery';
import { ElMessage,ElMessageBox } from 'element-plus';
import {selectSubjectLabel,selectSubjectMajor,addSubject,updateSubject,deleteSubject} from '@/api/subject'
import { useUserInfoStore } from "@/store/user.js";
import { select } from '@/api/common/work/work';
import { useTokenStore } from '@/store/token';



const subjectImage=ref();

const usertonken=useTokenStore()


//处理时间
const shijian=(time)=>{
   // 处理 createtime，推迟8个小时
   const processedItems = time.items.map(item => {
                if (item.createtime) {
                    const date = new Date(item.createtime);
                    date.setHours(date.getHours() + 16); // 推迟8个小时
                    item.createtime = date.toISOString().slice(0, 19).replace('T', ' ');
                }
                return item;
            });
            sysSubiect.value=processedItems
}

// 图片上传成功的回调
const uploadSuccess = (response, file) => {
  // 回显图片
  subjectImage.value = URL.createObjectURL(file.raw);
  forms.value.subjectImage = response.data; // 假设服务器返回的是图片URL
};
// 修改图片
const updatePicOne = async () => {
  let result = await updatePicService(imageUrl.value)
  if (result.code == 200) {
    // 更新 pinia 中的图片
    userInfoStore.userInfo.userAvatar = imageUrl.value
    ElMessage.success('修改成功')
  } else {
    ElMessage.error('修改失败')
  }
}
// 响应式变量
const importDialogVisible = ref(false);
// //删除
// const showCheckbox = ref(false);

// // 批量删除方法
// const batchDelete = async () => {
//   // 显示多选框
//   showCheckbox.value = true;
//   ww.value.deleted=1;

//   // 获取选中的题目ID列表
//   const selectedIds = sysSubiect.value
//     .filter(item => item.selected) // 假设每个题目对象有一个 selected 属性来标识是否被选中
//     .map(item => item.subjectId);

//   if (selectedIds.length === 0) {
//     ElMessage.warning('请选择要删除的题目');
//     return;
//   }

//   // 弹出确认对话框
//   ElMessageBox.confirm('确定要删除选中的题目吗?', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(async () => {
//     try {
//       // 调用删除接口
//       // const result = await deleteSubject(selectedIds);
//       // if (result.code === 200) {
//       //   ElMessage.success('删除成功');
//       //   // 刷新题目列表
//       //   getArticleList();
//       // } else {
//       //   ElMessage.error(result.msg);
//       // }
//     } catch (error) {
//       ElMessage.error('删除失败，请稍后再试');
//     }
//   }).catch(() => {
//     ElMessage.info('已取消删除');
//   });
// };

// const quxiaoshanchu=()=>{
//   ww.value.deleted=null;
//   showCheckbox.value = false;
//   resetForm();
// }


// const quxiaoxx = () => {
//   // 取消操作，隐藏多选框
//   showCheckbox.value = false;
//   resetForm();
// };

// const querxx = () => {
//   // 确认操作，隐藏多选框
//   showCheckbox.value = false;
//   // 其他确认操作
// };


// 下载模板的方法
const downloadTemplate = () => {
  const link = document.createElement('a');
  link.href = 'public/ti.xls'; // 根据实际路径调整
  link.download = 'ti.xls';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};


// 导入 Excel 方法
const importExcel = async (file) => {
  if (!file) {
    ElMessage.warning('请选择后缀为 “xls”或“xlsx”的文件。');
    return;
  }

  const formData = new FormData();
  formData.append('file', file.raw);
  formData.append('updateSupport', true);
  try {
     const result = await importSubject(formData);

    if (result.code === 200) {
      ElMessage.success(result.msg);
      importDialogVisible.value = false;
      getArticleList();
      // 刷新题目列表或其他操作
    } else {
      ElMessage.error('导入失败',result.msg);   
    }
  } catch (error) {
    ElMessage.error('导入失败',error);
  }
};

const xuanze = ref([
  {nanId:2,nanName:'单选题'},
  {nanId:1,nanName:'多选题'},
  {nanId:0,nanName:'判断题'}
])
//当前页
const pageNum=ref(1)
//每页显示条数
const pageSize=ref(10)
//总条数
const total=ref(50)
const loading = ref(false)
//所有题型
const sysSubiect=ref([]);
//难度
const sysSubjectLv=ref(0);
//专业
const zzid=ref(0);


// 定义选中的知识点数组
const selectedSubjects = ref([]);


//知识点选中
const selectedSubject = ref(null);

// 选择知识点的方法
const someNumber=ref([])

//开启加载
const startLoading = () => {
  loading.value = true
}
//关闭加载
const endLoading = () => {
  loading.value = false
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getArticleList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    if(someNumber.value!=null){
      tt()
    }else{
    getArticleList()
    }
    
}

// 切换知识点选中状态
const toggleSubject = (item) => {
   const index = selectedSubjects.value.findIndex(selectedItem => selectedItem.labelName === item.labelName);
  if (index > -1) {
    selectedSubjects.value.splice(index, 1); // 移除选中的知识点
  } else {
    selectedSubjects.value.push(item); // 添加选中的知识点
  }
  someNumber.value=selectedSubjects.value
  tt()

 
  
};
const ww=ref({
  data:someNumber.value,
  sysSubjectLv:sysSubjectLv.value,
  sysSubiectMajor:zzid.value,
  deleted:null
})
const tt=async()=>{
  let params={
    data:selectedSubjects.value,
    pageNum:pageNum.value,
    pageSize:pageSize.value,
    sysSubjectLv:sysSubjectLv.value,
    sysSubiectMajor:zzid.value
  }
  ww.value.data=selectedSubjects.value
  ww.value.sysSubjectLv=sysSubjectLv.value
  startLoading()
  let res=await selectSubjectByLabelId(params);
  endLoading()
  
    //sysSubiect.value=res.data.items
    shijian(res.data)
    total.value=res.data.total
 
}

//专业
const zz=(res)=>{
  zzid.value=res
  ww.value.sysSubiectMajor=zzid.value
  tt()
}

const selectSubject=(subject)=>{
  someNumber.value=subject.id
  selectedSubject.value = subject;
}

//获取题目列表
const getArticleList = async() => {
  let params={
    pageNum:pageNum.value,
    pageSize:pageSize.value
  }
  startLoading()
  const res = await selectAllQuestionTypeList(params);
  
 // sysSubiect.value = res.data.items.map(item => ({ ...item, selected: false })); // 初始化 selected 属性
 shijian(res.data)
  total.value = res.data.total;
  endLoading()
}

const lxData = ref([
  {nanId:1,nanName:'低'},
  {nanId:2,nanName:'中'},
  {nanId:3,nanName:'高'}
])
const zhuanye=ref([]);
//控制方向样式
const fxNum = ref(-1);
//控制类型
const lxNum = ref(-1);
//控制专业
const zyNum = ref(-1);

const dj = (index) => {
  someNumber.value = index
}
const dj1 = async(num) => {
  sysSubjectLv.value=num
  tt()
  
}

//点击全部方向
const dj2 = () => {
  someNumber.value = null
}
//点击全部类别
const dj3 = () => {
  someNumber.value = null
}

// 计算属性，过滤出单选题
const filteredRadioQuestions = computed(() => {
  return sysSubiect.value.filter(item => item);
});


//选择题目类型
const formInline = reactive({
  user: '',
  region: '',
  date: '',
})

// 清除弹框表单校验状态
const hc = ()=>{
  formRef.value={} 
}


//弹窗标题模型
const timu = ref("")

const xinzeng =()=>{
  forms.value={}
  tianjia.value = true;
  timu.value = "添加题目"
  selectSubjectLabelList();
  selectSubjectMajorList();
  formRef.value.resetFields(); // 清除表单校验状态
}

// 修改按钮点击事件
const xiugai = (item) => {
  selectSubjectLabelList();
  selectSubjectMajorList();
  tianjia.value = true;
  timu.value = "修改题目";
  
  // 直接将题目对象的值赋给 forms.value
  forms.value = { ...item };
  subjectImage.value = forms.value.subjectImage;

  // 将题目类型编号转换为名称
  const st = item.subjectType;
  switch(st) {
    case 0: 
      forms.value.subjectType = "判断题";
      break;
    case 1: 
      forms.value.subjectType = "多选题";
      break;
    case 2: 
      forms.value.subjectType = "单选题";
      break;
  }

  // 将难度编号转换为名称
  const nd = item.subjectLv;
  switch(nd) {
    case 1: forms.value.subjectLv = "低"; break;
    case 2: forms.value.subjectLv = "中"; break;
    case 3: forms.value.subjectLv = "高"; break;
  }

  // 将标签字符串转换为数字数组并赋值给 forms.value.subjectLabel
  if (Array.isArray(item.subjectLabel)) {
    labelsString.value = item.subjectLabel.map(Number);
  } else {
    labelsString.value = item.subjectLabel.split(',').map(Number);
  }
  forms.value.subjectLabel = labelsString.value;

  formRef.value.resetFields(); // 清除表单校验状态
};
const formRef = ref(null);

//弹出框表单校验证规则
const rules = computed(() => {
  return {
    subjectType: [
      { required: true, message: '请选择题目类型', trigger: 'change' },
    ],
    subjectName: [
      { required: true, message: '请输入题目名称', trigger: 'blur' },
    ],
    subjectMajor: [
      { required: true, message: '请选择专业名称', trigger: 'change' },
    ],
    subjectLabel: [
      { required: true, message: '请选择题目标签', trigger: 'change' },
    ],
    optionA: [
      { required: true, message: '请输入选项A', trigger: 'blur' },
    ],
    optionB: [
      { required: true, message: '请输入选项B', trigger: 'blur' },
    ],
    optionC: [
      { required: true, message: '请输入选项C', trigger: 'blur' },
    ],
    optionD: [
      { required: true, message: '请输入选项D', trigger: 'blur' },
    ],
    optionE: [
      { required: true, message: '请输入选项E', trigger: 'blur' },
    ],
    optionF: [
      { required: true, message: '请输入选项F', trigger: 'blur' },
    ],
    subjectAnswer: [
      { required: true, message: '请输入题目答案', trigger: 'blur' },
    ],
    subjectLv: [
      { required: true, message: '请选择题目难度', trigger: 'change' },
    ],
  };
});

//弹框取消按钮
const quxiao = () => {
  tianjia.value = false;
  resetForm(); // 重置表单数据
};

// 弹框确认按钮
const quer = async () => {
        // 将题目类型名称转换回编号
        switch (forms.value.subjectType) {
          case "判断题":
            forms.value.subjectType = 0;
            break;
          case "多选题":
            forms.value.subjectType = 1;
            break;
          case "单选题":
            forms.value.subjectType = 2;
            break;
        }

        // 将难度名称转换回编号
        switch (forms.value.subjectLv) {
          case "低":
            forms.value.subjectLv = 1;
            break;
          case "中":
            forms.value.subjectLv = 2;
            break;
          case "高":
            forms.value.subjectLv = 3;
            break;
        }

        // 判断试题id是否存在
        if (forms.value.subjectId) {
          updateSubjects();
          getArticleList();
        } else {
          add();
          getArticleList();
        }
        tianjia.value = false;
        resetForm(); // 重置表单数据
};


const resetForm = () => {
  
  forms.value = {}; // 重置 forms 数据
  forms.value.subjectName = '';

  labelsString.value = []; // 重置标签数据
  subjectImage.value = ''; // 清空图片字段
  formRef.value.resetFields(); // 清除表单校验状态

};

const forms = ref({
  subjectType: '',
  subjectLv: '',
})

//定义弹框中试题标签类别集合
const labelsString = ref([]);


  // 确保 subjectLabel 是一个数组
  if (Array.isArray(forms.value.subjectLabel)) {
    labelsString.value = forms.value.subjectLabel.join(',');
  } else {
    labelsString.value = '';
  }

// 定义一个函数来获取当前时间并格式化
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  forms.value.changetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
//删除按钮点击事件
const shan=(item)=>{
  chu(item);
}
// 删除题目方法
const item = ref({});
// 删除题目方法
const chu = async (subjectId) => {
  try {
    // 确保 subjectId 是一个数字
    if (typeof subjectId !== 'number' || isNaN(subjectId)) {
      ElMessage.error('题目ID无效');
      return;
    }

    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确定要删除此题目吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 用户点击“确定”后执行删除操作
    const response = await deleteSubject(subjectId);

    if (response.code === 200) {
      ElMessage.success('删除成功');
      getArticleList();
    } else if (response.code === 400) {
      ElMessage.error('该题被使用，无法删除');
    } else {
      ElMessage.error('删除失败');
    }
    
  } catch (error) {
    // 如果用户点击“取消”，则不会进入这个 catch 块
    if (error !== 'cancel') {
      ElMessage.error(error.response.data.msg);
    }
  }
};
// 添加题目
// 添加题目
const add = async () => {
  const aa = useUserInfoStore().userInfo;
  forms.value.creator = aa.userId;
  forms.value.subjectImage = subjectImage.value; // 确保图片字段正确传递

  // 将 forms.subjectLabel 数组中的元素用逗号拼接成一个字符串
  const ss = labelsString.value.join(','); // 解包 ref 对象
  forms.value.subjectLabel = ss;

  // 确保 forms.subjectAnswer 是数组时，将其转换为逗号分隔的字符串
  if (Array.isArray(forms.value.subjectAnswer)) {
    forms.value.subjectAnswer = forms.value.subjectAnswer.join(',');
  }

  let result = await addSubject(forms.value);

  if (result.code == 200) {
    ElMessage.success('添加成功');
    await getArticleList(); // 确保异步操作完成后再刷新列表
    tianjia.value = false;
  } else {
    ElMessage.error('添加失败'); 
  }
};

// 修改题目
const updateSubjects = async () => {
  getCurrentTime();

  // 确保 subjectLabel 是一个数组
  if (Array.isArray(forms.value.subjectLabel)) {
    labelsString.value = forms.value.subjectLabel.join(',');
  } else {
    labelsString.value = '';
  }

  // 将拼接好的字符串赋值给 forms.value.subjectLabel
  forms.value.subjectLabel = labelsString.value;

  let res = await updateSubject(forms.value);
  if (res.code === 200) {
    ElMessage.success('修改成功');
    await getArticleList(); // 确保异步操作完成后再刷新列表
  } else {
    ElMessage.error('修改失败');
  }
};

//定义标签数据
const subjectLabel = ref([]);

//查询题目标签
const selectSubjectLabelList = async () => {
  let result = await selectSubjectLabel();
  subjectLabel.value = result.data;
};

//定义专业数据
const zhaun=ref([])
//查询专业名称
const selectSubjectMajorList = async () => {
  let result = await selectSubjectMajor();
  zhaun.value = result.data;
};

const subjecLabel=ref([])
//查询所有的标签(知识点)
const label=async()=>{
  const res = await selectAllQuestionType();
  subjecLabel.value=res.data
}
const difficulties=ref([
  {id:1,labelName:'低'},
  {id:2,labelName:'中'},
  {id:3,labelName:'高'}
])
const  selectedDifficulty=ref(null)

const selectDifficulty = (difficulty) => {
  selectedDifficulty.value = difficulty;
};
// 添加
const tianjia = ref(false)

const formLabelWidth = '140px'

const form = reactive({})

// 在上传图片之前的钩子，可以在这里进行文件类型、大小等校验
const beforeAvatarUpload = (file) => {
  const isJPGorPNG = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt500K = file.size / 1024 / 1024 < 0.5;

  if (!isJPGorPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt500K) {
    ElMessage.error('上传图片大小不能超过 500KB!');
  }
  return isJPGorPNG && isLt500K;
};
 
// 处理图片上传成功的逻辑
const handleImageUpload = (response, file) => {
  // 假设服务器返回的是一个包含图片URL的对象
  // form.imageUrl = response.data.url; // 如果服务器返回的是URL
  // 如果是本地预览，可以直接使用file的URL
  forms.imageUrl = URL.createObjectURL(file.raw);
};

const selectedOption = ref([])
const handleChange = (values) => {
  forms.value.subjectLabel = values;
}

const removeTag = (option) => {
  const index = form.region.indexOf(option.value);
  if (index > -1) {
    form.region.splice(index, 1);
  }
  handleChange(form.region); // 重新调用 handleChange 来更新 selectedOption
}

const activeIndex = ref('0');

const handleSelect = (index) => {
  activeIndex.value = index;
};

//查询专业
const zhuanyechaxun=async()=>{
  let res=await selectMajorList();
  if(res.code==200){
    zhuanye.value=res.data
  }else{
    ElMessage.error(res.msg)
  }
}

onMounted(() => {
  // 初始化数据
  label()
  zhuanyechaxun()
  getArticleList()
  // 监听题目类型变化，清空题目答案
  watch(
    () => forms.value.subjectType,
    (newType) => {
      // 清空题目答案
      forms.value.subjectAnswer = newType === 1 || newType === '多选题' ? [] : '';
    }
  );
})
</script>

<style lang='scss' scoped>
.avatar-uploader-icon{
  margin: 70px;
}
.tt{
 border: 2px dashed #d9d9d9; /* 始终显示虚线边框 */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 250px;
  height: 250px;
   transition: border-color 0.3s;
}
.tt:hover{
  border-color: #409EFF; /* 鼠标悬停时改变边框颜色 */
}
.avatar-uploader {
  width: 250px;
  height: 250px;
}
.tu{
  width: 200px;
  height: 200px;
}




.ti{
  position: relative;
  right: 40px;
}
.common-layout-header-title {
  margin-top: 20px;
}
.common-course-Quest {
  
  margin: 40px;
}
.common-course-Quest-item{
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 15px 20px 25px;
  border-radius: 10px;
  box-shadow: 15px 5px 10px 2px rgba(0, 0, 0, 0.1);
}
.common-course-Quest-item-left{
  display: flex;
  flex-direction: row;
  height: 50px;
  line-height: 50px;
  justify-content: space-between;
  color: #333;
  font-size: 14px;
}


.separator {
  width: 100%;
  height: 0.08px;
  background-color: #e3e3e3;
  margin: 1; 
}
.separator01 {
  width: 100%;
  height: 0.08px;
  background-color: #e3e3e3;
  margin: 1; 
}
.common-course-Quest-item-title{
  margin-left: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.common-course-Quest-item-title_ti{
  height: 35px;
  line-height: 35px;
  margin-left: 20px;
}
.common-course-Quest-item-title_time_left{
  margin-left: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.common-course-Quest-item-option{
  display: flex;

}
.option-container{
  margin-left: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.common-course-Quest-item-ti{
  width: 80%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.common-course-Quest-item-title_caozuo{
  width: 10%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}







.upload-demo {
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
 
.upload-demo:hover {
  border-color: #409EFF;
}
 
.upload-demo i {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  text-align: center;
  line-height: 120px;
  transition: all 0.3s;
}
 
.upload-demo:hover i {
  color: #409EFF;
}
 
.el-upload__tip {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin-top: 4px;
}
.el-rate{
  display: inline-flex;
  align-items: center;
}


// .common-course-Quest-zhishidian-item{
  
//   padding-top:20px;
//   padding-bottom: 20px;
//   display: flex;
//   flex-direction: row;
//   align-items: center;
//   gap: 10px; /* 子元素之间的间距为10px */
//   white-space: nowrap; /* 防止内容换行 */
//   max-width: 100%; /* 确保容器宽度不超过父元素 */
//   flex-wrap: wrap;/* 防止内容换行 */
//   cursor: pointer;/*鼠标指针样式 */
//   // display: none;
  
// }



// .common-course-Quest-zhishidian-item .el-button {
//   margin-left: 50px; /* 添加按钮之间的间距 */
// }
// .common-course-Quest-zhishidian-item span {
//   margin-left: 50px; /* 添加文字之间的间距 */
// }
.selected {
  
  background-color:rgba(209,20,49,0.3);
  font-weight: bold;
  color: #d11431;
}
// .common-course-Quest-zhishidian-title:hover .common-course-Quest-zhishidian-item{
//   display: block;
//   display: flex;
//   flex-wrap: wrap;
//   justify-content: space-between;
  
// }
.button-container {
  display: inline-block;
  margin-right: 10px; /* 按钮之间的间距 */
}
.button {
  white-space: nowrap; /* 防止按钮内的文本换行 */
}

.common-course-Quest-nandu{
  
  margin-left: 50px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.common-course-Quest-nandu-item div{
  
  margin-left: 14px;
  width: 60px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  cursor: pointer;
}

.common-course-Quest-nandu-item {
 
  width: 400px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

// .common-course-Quest-nandu-item div.selected {
//   background-color:rgba(209,20,49,0.3);
//   color: #d11431;
//   padding: 5px 20px;
//   border-radius: 5px;
// }
.quanbu{
  padding: 5px;
  width: 60px;
  text-align: center;
  border-radius: 5px;
}
.fabu{
  width: 60%;
  margin-left: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: #333;
}

.body-header {
  width: 90%;
  height: 55px;
  display: flex;
  margin-left: 60px;
  text-align: center;

}

.body-header ul {
  // border :2px solid #e5e5e5;
  //  height: 37px;
  // display: flex;
  // list-style: none;//去黑点
  // text-align: center;
  line-height: 37px;//字间距
  float: left;
  font-size: 16px;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap
}

.body-header ul li {
  display: flex;
  flex-direction: row;
  padding-left: 10px;
  padding-right: 10px;
  margin-right: 20px;
  cursor: pointer;
}

.body-header ul li:hover {
  height: 37px;
  line-height: 37px;
  list-style: none;
  background-color: #f5f5f5;
}
//点击效果
.header-01 {
  height: 37px;
  line-height: 37px;
  list-style: none;
  color: #f46250;
  background-color: #ffe8e0;
}

.header-01:hover {
  color: #d04b3f;
}
.common-course-Quest-item-title_point{
  // border: 1px solid red;
  width: 70px;
  display: flex;
  flex-direction: row;
  margin-right: 10px;
}

.option-text{
  margin: 3px 0;
  font-size: 14px;
}

</style>